package pro.softzhang.algo.lc0;

import pro.softzhang.algo.common.ListNode;
import pro.softzhang.algo.common.Utils;
import pro.softzhang.algo.flag.knowledge.KLinkedList;
import pro.softzhang.algo.flag.x.XOptimal;

/**
 * 83. 删除排序链表中的重复元素
 * https://leetcode.cn/problems/remove-duplicates-from-sorted-list
 */
@KLinkedList
public class LC83_RemoveDuplicatesFromSortedList {
    public static void main(String[] args) {
        // ListNode head = new ListNode(1, new ListNode(2, new ListNode(2)));
        // Utils.printLinkedList(new Solution().deleteDuplicates(head));
        ListNode head = new ListNode(1, new ListNode(1, new ListNode(2)));
        Utils.printLinkedList(new Solution1().deleteDuplicates(head));
    }

    /**
     *
     */
    @XOptimal
    static
    class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if (head == null) {
                return null;
            }
            ListNode p = head;
            while (p.next != null) {
                if (p.val == p.next.val) {
                    p.next = p.next.next;
                } else {
                    p = p.next;
                }
            }
            return head;
        }
    }

    /**
     *
     */
    static
    class Solution1 {
        public ListNode deleteDuplicates(ListNode head) {
            if(head == null) {
                return head;
            }

            ListNode p = head;
            while(p.next != null) {
                if(p.val == p.next.val) {
                    p.next = p.next.next;
                } else {
                    p = p.next;
                }
            }
            return head;
        }
    }
}
